﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microhard.Core.DBUtility;
using Microhard.Core;
using Microhard.Core.Algorithm;
using Microhard.Plat.CRM.Stores.Interface;
using Microhard.Plat.CRM.Stores.DataAccess;
using Microhard.Plat.CRM.Stores.DTO;
using Microhard.Plat.CRM.Stores.Msg;
using Microhard.Plat.CRM.Stores.Models;

namespace Microhard.Plat.CRM.Stores.Impls
{
    public class SubKAImpl : ISubKA
    {
        public bool IsNameDuplicate(Models.SubKAModel model)
        {
            Microhard_Plat_StoresEntities db = new Microhard_Plat_StoresEntities();
            var cnt = db.SubKAs.Count(n => n.Name == model.Name);
            return cnt > 0 ? true : false;
        }

        public Microhard.Core.DBUtility.ExecutedResult Add(Models.SubKAModel model)
        {
            ExecutedResult rtn = new ExecutedResult();
            Microhard_Plat_StoresEntities db = new Microhard_Plat_StoresEntities();
            var op = model.ToEntity();
            try
            {
                op.ManagementScopes.Add(new ManagementScope
                {
                    CreateTime = DateTime.Now,
                    ScopeID = Guid.NewGuid(),
                    SubID = op.SubID,
                    EmployeeID = this.scope.EmpInfo.EmployeeID
                });
                //将人员添加到管理范围汇总
                if (model.SubKAEmployees != null)
                {
                    model.SubKAEmployees.ForEach(s =>
                    {
                        op.ManagementScopes.Add(new ManagementScope
                        {
                            CreateTime = DateTime.Now,
                            ScopeID = Guid.NewGuid(),
                            SubID = op.SubID,
                            EmployeeID = s
                        });
                    });
                }

                db.SubKAs.AddObject(op);
                db.SaveChanges();
            }
            catch (System.Exception ex)
            {
                rtn.ErrorMsg.Add(DBOperationFailedStatus.AddFailed, SubKAMsg.AddFailed);
                Log.Error("ISubKA.Add", ex);
            }
            return rtn;
        }

        public Microhard.Core.DBUtility.ExecutedResult Update(Models.SubKAModel model)
        {
            ExecutedResult result = new ExecutedResult();
            Microhard_Plat_StoresEntities db = new Microhard_Plat_StoresEntities();
            var entity = db.SubKAs.SingleOrDefault(l => l.KAID == model.KAID);
            if (entity != null)
            {
                entity.Address = model.Address;
                entity.Cellphone = model.Cellphone;
                entity.Contractor = model.Contractor;
                //if (model.SubKAEmployees.Count > 0)
                //{
                //    List<EmployeeModel> todelete, toadd;
                //    var exist = entity.ManagementScopes.Where(p => p.Range == (int)Range.Saler).Select(x => x.Employee.ToModel()).ToList();
                //    AlgCompare.DataCompareForCreateAndDelete<EmployeeModel>(exist, model.SalerEmployees, new EmployeeCompaer(), out todelete, out toadd);
                //    if (todelete != null)
                //    {
                //        todelete.ForEach(t =>
                //        {
                //            var d = db.ManagementScopes.SingleOrDefault(m => m.EmployeeID == t.EmployeeID);
                //            db.DeleteObject(d);
                //        });
                //    }
                //    if (toadd != null)
                //    {
                //        toadd.ForEach(a =>
                //        {
                //            db.ManagementScopes.AddObject(new ManagementScope
                //            {
                //                CreateTime = DateTime.Now,
                //                ScopeID = Guid.NewGuid(),
                //                SubID = model.SubID,
                //                EmployeeID = a.EmployeeID,
                //                Range = (int)Range.Saler
                //            });
                //        });
                //    }
                //}
            }
            try
            {
                db.SaveChanges();
            }
            catch (Exception ex)
            {
                result.ErrorMsg.Add(DBOperationFailedStatus.UpdateFailed, SubKAMsg.UpdateFailed);
                Log.Error("ISubKA.Update", ex);
            }
            return result;
        }

        public Microhard.Core.DBUtility.ExecutedResult Delete(List<Guid> ids)
        {
            ExecutedResult result = new ExecutedResult();
            Microhard_Plat_StoresEntities db = new Microhard_Plat_StoresEntities();
            var entity = db.SubKAs.Where(l => ids.Contains(l.SubID));
            foreach (var e in entity)
            {
                //是否在使用
                if (e.CheckListSheets.Count == 0 && e.EmployeeCheckIns.Count == 0)
                {
                    var scopes = e.ManagementScopes.ToList();
                    foreach (var s in scopes)
                    {
                        db.ManagementScopes.DeleteObject(s);
                    }
                    db.SubKAs.DeleteObject(e);
                }
                else
                {
                    result.ErrorMsg.Add(DBOperationFailedStatus.DeleteFailed + e.Name, string.Format(SubKAMsg.IsInUsing, e.Name));
                }
            }
            if (result.ErrorMsg.Count == 0)
            {
                try
                {
                    db.SaveChanges();
                }
                catch (Exception ex)
                {
                    result.ErrorMsg.Add(DBOperationFailedStatus.DeleteFailed, SubKAMsg.DeleteFailed);
                    Log.Error("ISubKA.Delete", ex);
                }
            }
            return result;
        }

        public Microhard.Core.DBUtility.ExecutedResult Delete(Models.SubKAModel model)
        {
            throw new NotImplementedException();
        }

        public Models.SubKAModel GetModelByID(Guid id)
        {
            Microhard_Plat_StoresEntities db = new Microhard_Plat_StoresEntities();
            return db.SubKAs.SingleOrDefault(c => c.SubID == id).ToModel();
        }

        public Models.SubKAModel GetModelByModel(Models.SubKAModel model)
        {
            throw new NotImplementedException();
        }

        public List<Models.SubKAModel> Query(Models.SubKAModel Model, int pageIndex, int pageSize, out int totalCount)
        {
            Microhard_Plat_StoresEntities db = new Microhard_Plat_StoresEntities();
            IEnumerable<SubKA> entities = from b in db.SubKAs
                                          where b.KAID == Model.KAID
                                          && b.KA.CompanyID == this.scope.EmpInfo.CompanyID
                                          select b;
            totalCount = entities.Count();
            var pagedEntities = entities.OrderBy(p => p.CustomerCode).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            if (pagedEntities != null && pagedEntities.Count > 0)
            {
                var result = pagedEntities.Select(m => m.ToModel()).ToList();
                return result;
            }
            return new List<SubKAModel>();
        }

        public List<Models.SubKAModel> Query(Models.SubKAModel Model)
        {
            return new List<SubKAModel>();
        }


        public Microhard.Core.DBUtility.ScopeResult scope
        {
            set;
            get;
        }



        public bool IsKACode(string code)
        {
            Microhard_Plat_StoresEntities db = new Microhard_Plat_StoresEntities();
            var cnt = db.SubKAs.Count(s => s.CustomerCode == code);
            return cnt > 0 ? true : false;
        }


        public List<SubKAModel> GetSubKAByKAID(Guid kaid)
        {
            Microhard_Plat_StoresEntities db = new Microhard_Plat_StoresEntities();
            return (from b in db.SubKAs
                    where this.scope.PKID.Contains(b.SubID)
                    && b.KAID == kaid
                    && b.KA.CompanyID == this.scope.EmpInfo.EmployeeID
                    select b).ToList().Select(t => t.ToModel()).ToList();
        }

        public bool IsCustomeCodeDuplicate(string code)
        {
            Microhard_Plat_StoresEntities db = new Microhard_Plat_StoresEntities();
            var cnt = db.SubKAs.Count(n => n.CustomerCode == code);
            return cnt > 0 ? true : false;
        }


        public ExecutedResult UpdateSubKALocation(SubKAModel model)
        {
            ExecutedResult result = new ExecutedResult();
            Microhard_Plat_StoresEntities db = new Microhard_Plat_StoresEntities();
            var entity = db.SubKAs.SingleOrDefault(l => l.SubID == model.SubID);
            if (entity != null)
            {
                entity.Baidulng = model.Baidulng;
                entity.Baidulat = model.Baidulat;
            }
            try
            {
                db.SaveChanges();
            }
            catch (Exception ex)
            {
                result.ErrorMsg.Add(DBOperationFailedStatus.UpdateFailed, SubKAMsg.UpdateFailed);
                Log.Error("ISubKA.UpdateSubKALocation", ex);
            }
            return result;
        }
    }
}
